/***********************************************************
 * UserManage BucketManage
 ***********************************************************/
/**
 * 
 */

var User = {
		
		
		init :function(){
			
			$('#box').combogrid({ 
				panelWidth : 280, 
				idField : 'id', 
				editable : false,
				textField : 'type'+'='+'caps', 
				fitColumns:true,
			    multiple:true,
			    
				//url : 'content.json',
				data : [
				        { "id":"users=*",
					      "type":"users",
					      "caps":"*"
				        },
				        {"id":"users=read",
						  "type":"users",
				          "caps":"read"
					    },
					    {"id":"users=write",
					      "type":"users",
					      "caps":"write"
					    },
					    {"id":"users=read,users=write",
					     "type":"users",
					     "caps":"read,write"
					    },
					    
					    {"id":"buckets=*",
					     "type":"buckets",
				         "caps":"*"
					    },
					    {"id":"buckets=read",
				    	 "type":"buckets",
					     "caps":"read"
					    },
						{"id":"buckets=write",
						 "type":"buckets",
						 "caps":"write"
						},
						{"id":"buckets=read,buckets=write",
						 "type":"buckets",
						 "caps":"read,write"
						},
					    
					    {"id":"metadata=*",
					     "type":"metadata",
				         "caps":"*"
					    },
					    {"id":"metadata=read",
				    	 "type":"metadata",
					     "caps":"read"
					    },
						{"id":"metadata=write",
						 "type":"metadata",
						 "caps":"write"
						},
						{"id":"metadata=read,metadata=write",
						 "type":"metadata",
						 "caps":"read,write"
						},
						

					    {"id":"usage=*",
					     "type":"usage",
				         "caps":"*"
					    },
					    {"id":"usage=read",
				    	 "type":"usage",
					     "caps":"read"
					    },
						{"id":"usage=write",
						 "type":"usage",
						 "caps":"write"
						},
						{"id":"usage=read,usage=write",
						 "type":"usage",
						 "caps":"read,write"
						},
						

					    {"id":"zone=*",
					     "type":"zone",
				         "caps":"*"
					    },
					    {"id":"zone=read",
				    	 "type":"zone",
					     "caps":"read"
					    },
						{"id":"zone=write",
						 "type":"zone",
						 "caps":"write"
						},
						{"id":"zone=read,zone=readwrite",
						 "type":"zone",
						 "caps":"read,write"
						}
				        
    	              ],
    	              
    	              onLoadSuccess: function () { //加载完成后,设置默认值
    	            	  var value = $('#capsValues').val();
    	            	  value=value.substr(0,value.length-1);
    	            	  $('#box').combogrid('setValues',value);
    	            	  /*
    	            	  
    	            	  if(value==""){
    	            	  $('#box').combogrid('setValues',"");
    	            	  }*/
    	            	  
    	            	  /*var val = $(this).combogrid("getData");
    	            	  alert(val);*/
    	            	 /* var val = $(this).combobox("getData");
    	            	  alert(val);*/
    	            	  /*var uid = $('#capsId').val();
    	            	  $.ajax({
    	          			type : "post",
    	          			data : {uid: uid},,
    	          			url : baseURL + "/os/user/listByUserjson",
    	          			dataType : "json",
    	          			success : function(json) {
    	          				
    	          				//alert(json.user.id);
    	          			}
    	          		});*/
    	            	 //$('#box').combogrid('setValue','zone=write');
    	                  /*var val = $(this).combobox("getData");
    	                  for (var item in val[0]) {
    	                      if (item == "id") {
    	                          $(this).combobox("select", val[0][item]);
    	                      }
    	                  }*/
    	     			/*var qosType = $("#qosType").val();
    	     			var val = $(this).combobox("getData");
    	     			if(qosType==0){
    	     				$('#box').combobox('setValue',val[0].qosTypeId);
    	     			}else{
    	     				$('#box').combobox('setValue',val[1].qosTypeId);
    	     			}*/
    	              },
    	     			
				columns : [[ 
				             { field : 'id', 
				               title : '编号',
				               width : 100,
				               checkbox:true,
				             }, 
				             {
				               field : 'type',
				               title : '类型', 
				               width : 100,
				             }, {
				               field : 'caps',
				               title : '读写',
				               width : 100,
			               	}, 
				       ]]
				});
			/*$('#box').combogrid({
				panelWidth:400,
				//value:'请选择权限',
				idField:'id',
			    textField:'user',
			    fitColumns:true,
			    multiple:true,
			    colums:[[
			             {
			            	field:'id',
			            	title:'编号',
			            	width:100,
			            	checkbox:true,
			             },
			             {
			            	 field:'user',
			            	 title:'类型',
			            	 width:100,
			             },
			             {
			            	 field:'caps',
			            	 title:'读写',
			            	 width:100,
			             },
			             
			             ]],
			     data : [
							        {"id":1,
								      "type":"users",
								      "caps":"读写"
							        },
							        {"id":1,
									 "type":"buckets",
									 "caps":"读写"
									}
							        
			    	     ],
			             data : [
							        {"id":1,
								      "user":"q",
								      "email":"xx"
							        },
							        {"id":2,
									      "user":"w",
									      "email":"xrx"
									},
							        {"id":3,
									      "user":"rw",
									      "email":"frx"
									}
							        
			    	     ],
				data : [
				        {"qosTypeId":0,
					      "qosType":"IOPS",
				        },
				        {"qosTypeId":1,
				      	"qosType":localeMsg.lun.bandWidth,} 
				        ],
				valueField : 'qosTypeId',
				textField : 'qosType',
				onSelect : function(record) {
					lun.change(record);
				},
			  onLoadSuccess: function () { 
	            
				var qosType = $("#qosType").val();
				var val = $(this).combobox("getData");
				if(qosType==0){
					$('#box').combobox('setValue',val[0].qosTypeId);
				}else{
					$('#box').combobox('setValue',val[1].qosTypeId);
				}
	         }
				
			});
			*/
		},
		
		
		showAvailableBucket : function(element, type) {
			var userId = $(element).parent().siblings().find("input[name='userId']").val();
			var title = "分配桶";
			var url = baseURL + "/os/user/listAvailableBuckets";
			var param = {userId : userId};
			if (type) {
				param.type = type;
				title = "分配桶";
			}
			common.dialog({
				type : "get",
				url : url,
				param : param,
				title : title,
				width : 600,
				confirm : function(dialog) {
					var bucketIdsArr = [];
					$(dialog).find("input[name='bucketId']:checked").each(function() {
						bucketIdsArr.push($(this).val());
					});
					
					User.linkBucket(userId, bucketIdsArr);
				},
				onOpen : function() {
					/*if (type != "other") {
						$(".l-btn-selected span.l-btn-text").text(localeMsg.common.deleted);
					}*/
				}
			});
		},
		
		linkBucket : function(uid, bucketIdsArr) {
			//alert(uid+"====="+bucketIdsArr+"-----");
			$.ajax({
				type : "post",
				url : baseURL + "/os/user/linkBucket",
				traditional: true,
				data : {uid: uid, bucketNames : bucketIdsArr},
				dataType : "json",
				success : function(json) {
					common.showTip({
						title : localeMsg.common.prompt,
						text : "分配成功",
						success : true
					});
				}
			});
		},
		showUserBucket : function(element, type) {
			var uid = $(element).parent().siblings().find("input[name='userId']").val();
			var title = localeMsg.host.list;
			var url = baseURL + "/os/user/showBuckets";
			var param = {uid : uid};
			if (type) {
				param.type = type;
				title = localeMsg.host.add;
			}
			common.dialog({
				type : "get",
				url : url,
				param : param,
				title : title,
				width : 600,
				confirm : function(dialog) {
					var bucketNamesArr = [];
					$(dialog).find("input[name='bucketId']:checked").each(function() {
						bucketNamesArr.push($(this).val());
					});
					
					User.unlinkBucket(uid, bucketNamesArr);
				},
				onOpen : function() {
					$(".l-btn-selected span.l-btn-text").text(localeMsg.common.deleted);
				}
			});
		},
		
		unlinkBucket : function(uid, bucketNamesArr) {
			//alert(uid+"====="+bucketIdArr+"-----");
			$.ajax({
				type : "post",
				url : baseURL + "/os/user/unlinkBucket",
				traditional: true,
				data : {uid: uid, bucketNames : bucketNamesArr},
				dataType : "json",
				success : function(json) {
					common.showTip({
						title : localeMsg.common.prompt,
						text : "移除成功",
						success : true
					});
				}
			});
		},
	
	bucketManage : function() {
		var uid = $("#usersList input[name='userId']:checked").val();
		/*alert(uid);*/
		var url = baseURL + "/os/user/showBuckets";
		var param = {uid : uid};
		if(uid == undefined){
			common.showTip({
				title : localeMsg.common.prompt,
				text : localeMsg.common.selectMsg
			});
		}else{
			common.dialog({
				type : "get",
				url : url,
				param : param,
				title : "桶管理",
				width : 900,
				/*confirm : function(dialog) {
					var lunArr = [];
					$(dialog).find("input[name='lunId']:checked").each(function() {
						lunArr.push($(this).val());
					});
					Group.unmapping(groupId, lunArr);
				}*/
			});
		}
	},	
	addCaps : function() {
		
		var userIds =[];
		$("input[name='userId']:checked").each(function(){
			userIds.push($(this).val()); 
            });
		var title = "设置权限";
		var param = {};
		if(userIds.length==0){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else if(userIds.length>1){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else{
			var userId = $("input[name='userId']:checked").eq(0).val();
			/*var capsOldValue = $('#capsValues').val();
			capsOldValue=capsOldValue.substr(0,value.length-1);
			alert(capsOldValue);*/
			title = "设置权限";
			param.userId = userId;
			common.dialog({
				//obj : "#editHostDialog",
				type : "get",
				url : baseURL + "/os/user/addCaps",
				param : param,
				title : title,
				width : 400,
				confirm : function() {
					/*if($("#editHostForm").form('validate')!=true){
						return;
					}
					Host.save();*/
					
					User.saveCaps();
				}
			});
		}
	},

	saveCaps :function(){
		var uid = $('#capsId').val();
		var capsOldValue = $('#capsValues').val();
		capsOldValue=capsOldValue.substr(0,capsOldValue.length-1);
		
		//alert(capsOldValue);
		var caps = $('#box').combobox('getValues');
		
		//alert(caps);
		
		/*
		if(capsOldValue==""){alert(caps);
		var newCaps = caps.substr(0,caps.length-1);
			caps = $('#box').combogrid('setValues',newCaps);
		}
		*/
		
		
		
		/*caps=caps.substr(0,caps.length-1);*/
		//alert(uid);
		$.ajax({
			type : "post",
			url : baseURL + "/os/user/saveCaps",
			traditional: true,
			data : {uid: uid, caps : caps, capsOldValue : capsOldValue},
			dataType : "json",
			success : function(json) {
				common.showTip({
					title : localeMsg.common.prompt,
					text : "设置权限成功",
					success : true,
					callback : function() {
						User.listUser();
					}
				});
			}
		});
		/*$("#qosForm").ajaxSubmit({
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : "Succeed to qos!",
						success: true,
						callback : function() {
							lun.list();
						}
					});
				} else {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.saveFailed,
						success: false
					});
				}
			},
		});*/
	},
	
	listUser : function() {location.reload();
		/*var ListUrl = baseURL + "/os/user"
		$.ajax({
			type : "get",
			url : ListUrl,
			dataType : "html",
			success : function(html) {
				// Request successfully and fill the data.
				$("#content").empty().html(html);
			}
		});*/
	},
	/**
	 * New bucket
	 */
	createBucket : function() {
		var title = "创建桶";
		common.dialog({
			obj : "#editHostDialog",
			type : "get",
			url : baseURL + "/os/bucket/create",
			title : title,
			width : 400,
			confirm : function() {
				if($("#createBucketForm").form('validate')!=true){
					return;
				}
				User.saveBucket();
			}
		});
	},
	saveBucket : function() {
		$("#createBucketForm").ajaxSubmit({
			success : function(json) {
				// Save successfully and refresh the user list.
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : localeMsg.common.saveSuccess,
						success : true,
						callback : function() {
							User.listBucket();
						}
					});
				} else {
					common.showTip({title : localeMsg.common.warn, text : localeMsg.common.saveFailed});
				}
			}
		});
	},
	listBucket : function() {
		// Request user list url.
		var BucketListUrl = baseURL + "/os/bucket/list"
		$.ajax({
			type : "get",
			url : BucketListUrl,
			dataType : "html",
			success : function(html) {
				// Request successfully and fill the data.
				$("#bucketsList").empty().html(html);
			}
		});
	},

	removeBucket : function(){
		var bucketId=[];
		$('input[name="bucketName"]:checked').each(function(){
			bucketId.push($(this).val()); 
            });  
		if (Object.keys(bucketId).length === 0){
			common.showTip({
				title : localeMsg.common.warn,
				text : localeMsg.common.selectMsg 
			});
		}else{
			var confirmMessage = localeMsg.common.deleteConfirm
			common.confirmDialog(confirmMessage,User.removeBucketDel);
		}

	},
	
	removeBucketDel : function() {
		
		var bucketIds=[];
		$('input[name="bucketName"]:checked').each(function(){
			bucketIds.push($(this).val()); 
		});  
		
		$.ajax({
			type : "post",
			url : baseURL + "/os/bucket/remove",
			data : {bucketNames : bucketIds},
			traditional: true,
			dataType : "json",
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : localeMsg.common.deleteSuccess ,
						success : true,
						callback : function() {
							User.listBucket();
						}
					});
				} else {
					common.showTip({title : localeMsg.common.warn, text : localeMsg.common.deleteFail});
				}
			}
		});
	
    },
     quota : function() {
		
		var userIds =[];
		$("input[name='userId']:checked").each(function(){
			userIds.push($(this).val()); 
            });
		var title = "设置配额";
		var param = {};
		if(userIds.length==0){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else if(userIds.length>1){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else{
			var userId = $("input[name='userId']:checked").eq(0).val();
			/*var capsOldValue = $('#capsValues').val();
			capsOldValue=capsOldValue.substr(0,value.length-1);
			alert(capsOldValue);*/
			title = "设置配额";
			param.userId = userId;
			common.dialog({
				//obj : "#editHostDialog",
				type : "get",
				url : baseURL + "/os/user/quota",
				param : param,
				title : title,
				width : 500,
				confirm : function() {
					if($("#saveQuotaForm").form('validate')!=true){
						return;
					}
					User.saveQuota(userId);
				}
			});
		}
	},
	saveQuota : function(userId) {
		$("#saveQuotaForm").ajaxSubmit({
			data :{userId:userId},
			type :"post",
			success : function(json) {
				// Save successfully and refresh the user list.
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : "配额设置成功",
						success : true,
						callback : function() {
							User.listUser();
						}
					});
				} else {
					common.showTip({title : localeMsg.common.warn, text : localeMsg.common.saveFailed});
				}
			}
		});
	},
	
	showQuota : function(){
		$('#usersList td[name="quota"]').each(function(){
			var userId = $(this).attr("id");
			var s = $(this);
			$.ajax({
				type : "post",
				url : baseURL + "/os/user/quotaByJson",
				data : {userId : userId},
				dataType : "json",
				success : function(json) {
					s.empty().append("桶&nbsp;maxsize:"+json.userBucketQuota.params.max_size_kb+"&nbsp;&nbsp;"+"maxobjects:"+json.userBucketQuota.params.max_objects+"<br>"+"用户maxsize:"+json.userUserQuota.params.max_size_kb+"&nbsp;&nbsp;"+"maxobject:"+json.userUserQuota.params.max_objects);
					//s.text(json.userUserQuota.params.max_size_kb);
					//s.text("bq=maxsize=="+json.userBucketQuota.params.max_size_kb+"=maxobj=="+json.userBucketQuota.params.max_objects+"<br>"+"uq=maxsize=="+json.userUserQuota.params.max_size_kb+"=maxobj=="+json.userUserQuota.params.max_objects);
					//$(this).text("d");
					//alert(json.userUserQuota.params.max_size_kb);
					/*if (json.result && json.result == "success") {
						common.showTip({
							title : localeMsg.common.prompt,
							text : localeMsg.common.deleteSuccess ,
							success : true,
							callback : function() {
								User.listBucket();
							}
						});
					} else {
						common.showTip({title : localeMsg.common.warn, text : localeMsg.common.deleteFail});
					}*/
				}
			});
			
			
			
	     });
	},
	
	modifyMaxBuckets : function() {
			
			var userIds =[];
			$("input[name='userId']:checked").each(function(){
				userIds.push($(this).val()); 
	            });
			var title = "基础设置";
			var param = {};
			if(userIds.length==0){
				common.showTip({
					title : localeMsg.common.warn ,
					text : localeMsg.common.selectMsg
				});
			}else if(userIds.length>1){
				common.showTip({
					title : localeMsg.common.warn ,
					text : localeMsg.common.selectMsg
				});
			}else{
				var userId = $("input[name='userId']:checked").eq(0).val();
				title = "基础设置";
				param.userId = userId;
				common.dialog({
					//obj : "#editHostDialog",
					type : "get",
					url : baseURL + "/os/user/showMaxBuckets",
					param : param,
					title : title,
					width : 500,
					confirm : function() {
						if($("#saveMaxBucketsForm").form('validate')!=true){
							return;
						}
						User.saveMaxBuckets();
					}
				});
			}
		},
	
		saveMaxBuckets : function() {
			$("#saveMaxBucketsForm").ajaxSubmit({
				success : function(json) {
					// Save successfully and refresh the user list.
					if (json.result && json.result == "success") {
						common.showTip({
							title : localeMsg.common.prompt,
							text : localeMsg.common.saveSuccess,
							success : true,
							callback : function() {
								User.listUser();
							}
						});
					} else {
						common.showTip({title : localeMsg.common.warn, text : localeMsg.common.saveFailed});
					}
				}
			});
		},
		
		/*
		suspended : function() {
			
			var userIds =[];
			$("input[name='userId']:checked").each(function(){
				userIds.push($(this).val()); 
	            });
			var title = "设置挂起";
			var param = {};
			if(userIds.length==0){
				common.showTip({
					title : localeMsg.common.warn ,
					text : localeMsg.common.selectMsg
				});
			}else if(userIds.length>1){
				common.showTip({
					title : localeMsg.common.warn ,
					text : localeMsg.common.selectMsg
				});
			}else{
				var userId = $("input[name='userId']:checked").eq(0).val();
				title = "设置挂起";
				param.userId = userId;
				common.dialog({
					//obj : "#editHostDialog",
					type : "get",
					url : baseURL + "/os/user/showSuspended",
					param : param,
					title : title,
					width : 500,
					confirm : function() {
						if($("#saveMaxBucketsForm").form('validate')!=true){
							return;
						}
						User.saveMaxBuckets();
					}
				});
			}
		},*/
	
	validate : function(){
		$('#targetName').validatebox({
			required : true,
			validType :	['vername','uniquename["/mapping/target/validateName"]']
		});
		$('#targetIp').validatebox({
			required : true,
			validType : 'ip'
		});
	}
	
	
};

